package com.aim.controller.system;

import com.aim.common.annotion.Permission;
import com.aim.common.base.AjaxResult;
import com.aim.common.entity.ZTreeNode;
import com.aim.common.service.ZtreeNodeService;
import com.aim.common.util.*;
import com.aim.config.shiro.ShiroKit;
import com.aim.entity.system.SysRole;
import com.aim.service.system.SysRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;

/**
 * @AUTO 角色控制器
 * @Author AIM
 * @DATE 2019/4/26
 */
@Controller
@RequestMapping("/role")
public class SysRoleController {

	private static String PREFIX = "system/role/";

	@Autowired
	private SysRoleService roleService;
	@Autowired
	private ZtreeNodeService ztreeNodeService;
	@Autowired
	private JdbcTemplate jdbcTemplate;

	/**
	 * 列表页面
	 */
	@RequestMapping("")
	public String index() {
		return PREFIX + "list.html";
	}

	/**
	 * 查询列表
	 */
	@PostMapping("/list")
	@Permission
	@ResponseBody
	public Object list(HttpServletRequest request) {
		Map<String, Object> params = WebUtil.getRequestMap(request);
		// 设定当前页码，以及当前页显示的条数
		PageHelper.startPage(PageUtil.getPageNum(params), PageUtil.getPageSize(params));
		List<SysRole> list = roleService.findList(params);
		PageInfo<SysRole> pageInfo = new PageInfo<SysRole>(list);
		return AjaxResult.success((int) pageInfo.getTotal(), list);
	}

	/**
	 * 添加编辑页面
	 */
	@Permission
	@RequestMapping(value = {"/add", "/update"})
	public String editView(String id, Model model) {
		if (OftenUtil.isNotEmpty(id)) {
			SysRole sysRole = roleService.get(ConverterUtils.toLong(id));
			model.addAttribute("role", sysRole);
		}
		return PREFIX + "edit.html";
	}

	/**
	 * 保存
	 */
	@PostMapping("/save")
	@ResponseBody
	public Object save(SysRole roles) {
		SysRole sysRole = this.roleService.get(roles.getRoleId());
		if (null == sysRole) {
			roles.setCreateTime(new Date());
			roles.setCreateUser(ShiroKit.getUser().getUserId());
			this.roleService.save(roles);
		} else {
			BeanUtils.copyProperties(roles, sysRole);
			sysRole.setUpdateTime(new Date());
			sysRole.setUpdateUser(ShiroKit.getUser().getUserId());
			this.roleService.update(sysRole);
		}
		return AjaxResult.success();
	}

	/**
	 * 删除
	 *
	 * @param ids 删除ID集合
	 */
	@Permission
	@PostMapping("/del")
	@ResponseBody
	public Object del(String ids) {
		if (OftenUtil.isNotEmpty(ids)) {
			List<String> dels = ConverterUtils.list(false, ids.split(","));
			ConverterUtils.listRemove(dels, "1");
			int size = dels.size();
			if (size > 0) {
				String[] strs = dels.toArray(new String[size]);
				this.roleService.batchDelete(strs);
				return AjaxResult.success();
			} else {
				return AjaxResult.error("含有不能删角色");
			}
		} else {
			return AjaxResult.error("参数异常");
		}
	}

	/**
	 * 获取部门的tree列表
	 */
	@RequestMapping(value = "/tree")
	@ResponseBody
	public Object tree() {
		List<ZTreeNode> tree = this.ztreeNodeService.roleZtree();
		tree.add(ZTreeNode.createParent());
		return AjaxResult.success(tree);
	}

	/**
	 * 设置角色页面
	 */
	@RequestMapping("/setAssign")
	public String setRoleView(String id, Model model) {
		if (OftenUtil.isNotEmpty(id)) {
			StringBuffer sb = new StringBuffer("SELECT MENU_ID FROM `sys_role_menu` WHERE `ROLE_ID` = ?");
			List<String> list = this.jdbcTemplate.queryForList(sb.toString(), new Object[]{id}, String.class);
			model.addAttribute("menuIds", WebUtil.join(",", list));
		}
		model.addAttribute("roleId", id);
		return PREFIX + "permiss.html";
	}

	/**
	 * 保存
	 */
	@Permission
	@PostMapping("/saveAssign")
	@ResponseBody
	public Object saveAssign(final String roleId, String menus) {
		try {
			StringBuffer sb = new StringBuffer("DELETE FROM `sys_role_menu` WHERE ROLE_ID = ?");
			this.jdbcTemplate.update(sb.toString(), new Object[]{roleId});
			sb.setLength(0);
			sb.append("INSERT INTO `sys_role_menu` (`MENU_ID`,`ROLE_ID`) VALUES (?,?)");
			final List<String> list = Arrays.asList(menus.split(","));
			this.jdbcTemplate.batchUpdate(sb.toString(), new BatchPreparedStatementSetter() {
				@Override
				public int getBatchSize() {
					return list.size();
				}

				@Override
				public void setValues(PreparedStatement ps, int i) throws SQLException {
					ps.setObject(1, list.get(i));
					ps.setObject(2, roleId);
				}
			});
			return AjaxResult.success();
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("保存权限失败");
		}
	}
}
